<template>
  <div>
    <div v-if="device !== 'mobile'" class="app-container">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline"
        v-hasPermi="['after:workorder:query']">
        <el-form-item label="单位" prop="name">
          <el-input v-model.trim="queryParams.name" :maxlength="15" size="small" placeholder="请输入单位名称"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" size="small" clearable filterable placeholder="请选择类型"
            style="width: 100%;">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单来源" prop="source">
          <el-select v-model="queryParams.source" size="small" clearable filterable placeholder="请选择类型"
            style="width: 100%;">
            <el-option v-for="item in projectType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态" prop="status">
          <el-select v-model="queryParams.status" size="small" clearable filterable placeholder="请选择工单状态"
                     style="width: 100%;">
            <el-option v-for="item in dict.type.sys_workorder_status" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="principalName">
          <el-input v-model="queryParams.principalName" placeholder="请填写负责人" :maxlength="20" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-search" @click="searchHandler">查询</el-button>
          <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="20">
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['after:workorder:add']"
              @click="openDialog(null)">增加</el-button>
            <!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['md:activity:export']" @click="exportHandler">导出</el-button>-->
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple"></div>
        </el-col>
      </el-row>

      <el-table ref="tableRef" :data="tableData" highlight-current-row max-height="680" v-loading="loading"
        v-horizontal-scroll="'auto'" style="width: 100%;margin-top: 10px;">
        <el-table-column type="index" width="50" align="center" label="序号">
          <template slot-scope="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column property="type" label="工单类型" align="center" width="100" />
        <el-table-column property="source" label="工单来源" align="center" width="100" />
        <el-table-column property="projectNo" label="项目编号" align="center" width="100" />
        <el-table-column property="name" label="名称" align="center" min-width="120" />
        <el-table-column property="secondarySector" label="二级部门" align="center" min-width="120" />
        <el-table-column property="contactName" label="联系人" align="center" width="100" />
        <el-table-column property="contactPhone" label="联系电话" align="center" width="120" />
        <el-table-column property="address" label="客户地址" align="center" width="180" />
        <el-table-column property="product" label="产品名称" align="center" width="120" />
        <el-table-column property="serviceContent" label="服务内容" align="center" />
        <el-table-column property="status" label="工单状态" align="center" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_workorder_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column property="planTime" label="计划时间" align="center" width="120" />
        <el-table-column property="description" label="描述" align="center" />
        <el-table-column property="principalName" label="负责人" align="center" width="120" />
        <el-table-column property="synergyName" label="协同人" align="center" />
        <el-table-column property="finishTime" label="完成时间" align="center" width="120" />
        <el-table-column property="remark" label="备注" align="center" />
        <el-table-column property="createBy" label="创建人" align="center" width="120" />
        <el-table-column property="createTime" label="创建时间" align="center" width="160" sortable />
        <el-table-column label="操作" align="center"
          v-if="$auth.hasPermi('after:workorder:edit') || $auth.hasPermi('after:workorder:remove') || $auth.hasPermi('after:workorder:view') || $auth.hasPermi('after:workorder:assign')">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-view" v-hasPermi="['after:workorder:view']"
              @click="handleView(scope.row)">查看</el-button>
            <el-button v-if="scope.row.status !== '已完成' && $auth.hasPermi('after:workorder:edit')" type="text" icon="el-icon-edit"
              @click="openDialog(scope.row)">修改</el-button>
            <el-button v-if="scope.row.status === '待分配' && scope.row.status !== '已完成'" type="text" icon="el-icon-s-promotion"
              v-hasPermi="['after:workorder:assign']" @click="showSell(scope.row)">指派</el-button>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
              @confirm="deleteHandler(scope.row)">
              <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['after:workorder:remove']"
                type="text" style="margin-left: 10px">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <div v-else style="height: calc(100vh - 90px);overflow: auto;" class="infinite-box app-container">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline"
               v-hasPermi="['after:workorder:query']">
        <el-form-item label="单位" prop="name">
          <el-input v-model.trim="queryParams.name" :maxlength="15" size="small" placeholder="请输入单位名称"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" size="small" clearable filterable placeholder="请选择类型"
                     style="width: 100%;">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单来源" prop="source">
          <el-select v-model="queryParams.source" size="small" clearable filterable placeholder="请选择类型"
                     style="width: 100%;">
            <el-option v-for="item in projectType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态" prop="status">
          <el-select v-model="queryParams.status" size="small" clearable filterable placeholder="请选择工单状态"
                     style="width: 100%;">
            <el-option v-for="item in dict.type.sys_workorder_status" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-search" @click="searchHandler">查询</el-button>
          <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="20">
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['after:workorder:add']"
                       @click="openDialog(null)">增加</el-button>
            <!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['md:activity:export']" @click="exportHandler">导出</el-button>-->
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple"></div>
        </el-col>
      </el-row>

      <ul class="infinite-list" v-infinite-scroll="handleLoad">
        <li v-for="item in tableData" :key="item.id" class="infinite-list-item">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{ item.type }}</span>
              <div style="float: right;">
                <el-button v-if="item.status != '已完成' || $auth.hasPermi('after:workorder:edit')" type="text"
                           @click="openDialog(item)" style="padding: 3px 0">修改</el-button>
                <el-button v-if="item.status === '待分配' && item.status != '已完成'" type="text"
                           v-hasPermi="['after:workorder:assign']" @click="showSell(item)" style="padding: 3px 0">指派</el-button>
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
                               @confirm="deleteHandler(item)">
                  <el-button slot="reference" v-hasPermi="['after:workorder:remove']"
                             type="text" style="margin-left: 10px;padding: 3px 0">删除</el-button>
                </el-popconfirm>
              </div>
            </div>
            <div class=" cus_text" @click="handleView(item)">
              <div class="flex">
                <span>单位名称: </span>
                <span class="flex-1">{{ item.name }}</span>
              </div>
              <div class="flex">
                <span>联系人: </span>
                <span class="flex-1">{{ item.contactName }}</span>
              </div>
              <div class="flex">
                <span>联系电话: </span>
                <span class="flex-1">{{ item.contactPhone }}</span>
              </div>
              <div class="flex items-center">
                <span>状态: </span>
                <div class="flex-1">
                  <dict-tag :options="dict.type.sys_workorder_status" :value="item.status"/>
                </div>
              </div>
              <div class="flex">
                <span>产品名称: </span>
                <span class="flex-1">{{ item.product }}</span>
              </div>
              <div class="flex">
                <span>服务内容: </span>
                <span class="flex-1">{{ item.serviceContent }}</span>
              </div>
              <div class="flex">
                <span>计划时间: </span>
                <span class="flex-1">{{ item.planTime }}</span>
              </div>
            </div>
          </el-card>
        </li>
      </ul>

      <div v-if="loading" style="text-align: center;color: #909399;"><i class="el-icon-loading"></i> 正在加载</div>
      <div v-else-if="tableData.length <= 0" style="text-align: center;color: #909399;">暂无数据</div>
      <div v-else-if="!queryParams.hasNextPage" style="text-align: center;color: #909399;">暂无更多数据</div>

      <el-backtop target=".infinite-box"></el-backtop>
    </div>

    <CreateAfterOrder :dialogTitle="dialogTitle" :show.sync="dialogVisible" :info="form" @add="addHandler"
      @update="updateHandler" />

    <el-dialog title="执行人" :visible.sync="userVisible" width="800px" :close-on-press-escape="false" destroy-on-close
      close-on-click-modal :fullscreen="device === 'mobile'">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="90px" class="demo-form"
        :label-position="device === 'mobile' ? 'top' : 'right'">
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="负责人" prop="principalId">
              <el-select v-model="form.principalId" allow-create clearable filterable placeholder="请选择负责人"
                style="width: 100%;">
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="协同人" prop="synergyIds">
              <el-select v-model="form.synergyIds" multiple allow-create clearable filterable placeholder="请选择协同人"
                style="width: 100%;">
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="sellForm('formRef')">下一步</el-button>
        <el-button @click="userVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deleteDataApi, getDataListApi, updateDataApi } from "@/api/after/workorder";
import CreateAfterOrder from '@/views/components/CreateAfterOrder'
import { getUserProfile, listUser } from "@/api/system/user";
import { mapGetters } from 'vuex'
import { throttle } from "@/utils";

export default {
  name: 'WorkorderView',
  dicts: ['sys_workorder_status'],
  components: { CreateAfterOrder },
  data() {
    return {
      // 执行人弹窗
      userVisible: false,
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 加载动画
      loading: true,
      // 活动日期
      activityDate: [],
      // 省份数据
      // provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        secondarySector: "", // 二级部门
        id: null,
        workorderId: null,
        type: "售后维修", // 工单类型（调试验收、售后走访、现场维修、培训大赛）
        source: "客户", // source工单来源（客户、合作伙伴）
        name: "", // 客户/合作伙伴 名称
        contactName: "", // 联系人名称
        contactPhone: "",
        contactId: null,
        address: "", // 地址
        planTime: "", // 计划时间
        serviceContent: "", // 服务内容
        product: "", // 产品
        image: "",
        remark: "",
        finishTime: "", // 完成时间
        principalId: "", // 负责人ID
        synergyId: "", // 协同人ID
        synergyIds: [], // 协同人ID
        principalName: "", // 负责人名称
        synergyName: "", // 协同人名称
        description: "", // 描述
        status: "待分配", // 工单状态：（待分配、已指派、已接受、进行中、已完成、已暂停）
      },
      // 表单的校验规则
      rules: {
        principalId: [
          { required: true, message: '请选择负责人', trigger: 'change' }
        ],
      },
      // 工单来源类型
      projectType: [
        {
          value: "客户",
          label: "客户"
        },
        {
          value: "代理商",
          label: "代理商"
        }
      ],
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        principalName: "",
        menuType: 1,
        status: "", // 工单状态
        source: "", // 工单来源
        name: "", // 创建人 *
        type: null, // 类型 *
        pageNum: 1,
        pageSize: 10,
        pages: 0, // 总页数
        hasNextPage: false, // 还有下一页
      },
      // 类型
      typeList: [
        {
          label: "调试验收",
          value: "调试验收"
        },
        {
          label: "售后走访",
          value: "售后走访"
        },
        {
          label: "现场维修",
          value: "现场维修"
        },
        {
          label: "培训大赛",
          value: "培训大赛"
        },
        {
          label: "售后维修",
          value: "售后维修"
        }
      ],
      // 代理商数据
      agentList: [],
      // 客户数据
      customerList: [],
      // 二级部门数据
      schoolList: [],
      // 联系人数据
      contactList: [],
      // 图片列表
      fileList: [],
      // 产品列表
      productList: [],
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 用户列表
      userList: [],
    }
  },
  watch: {
    activityDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
  },
  computed: {
    ...mapGetters([
      'device'
    ])
  },
  created() {
    this.getList()
    this.getUserinfo()
    this.getUserList()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 下拉加载
    handleLoad: throttle(function () {
      if(!this.queryParams.hasNextPage) {
        return false
      }
      this.queryParams.pageNum += 1
      this.getList({ isConnect: true })
    }, 2000),
    handleView(row) {
      this.$router.push({ name: "WorkorderDetail", query: {workorderId: row.id}})
    },
    // 获取用户列表
    getUserList() {
      listUser({
        pageSize: 500,
      }).then(response => {
        this.userList = (response.rows ?? []).filter(i => !i.admin)
      }
      );
    },
    // 完成派发
    sellForm(formName) {
      const _this = this
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const payload = {
            ..._this.form,
            status: "已指派",
            updateBy: _this.user.nickName,
          }
          const res = await updateDataApi(payload)
          if (res.code === 200) {
            _this.$message({
              message: res.msg,
              type: 'success'
            });
            this.getList()
            // 跳转到工单详情页
            this.userVisible = false
            this.handleView(_this.form)
          } else {
            _this.$message({
              message: res.msg,
              type: 'error'
            });
          }
        }
      })
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList(options) {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        if(options?.isConnect) {
          const list = res.data.list ?? []
          this.tableData = [...this.tableData, ...list]
        } else {
          this.tableData = res.data.list ?? []
        }
        this.total = res.data.total ?? 0
        this.queryParams.pages = res.data.pages ?? 0
        this.queryParams.hasNextPage = res.data.hasNextPage
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开执行人弹窗
    showSell(row) {
      this.form = { ...row }
      this.userVisible = true
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {

        this.formId = row.id

        let synergyIds = []
        if(typeof row.synergyIds === 'string') {
          synergyIds = (row.synergyIds ?? "").split(',').filter(i => i) ?? []
        } else {
          synergyIds = (row.synergyIds ?? []).map(i => +i)
        }

        this.form = {
          ...row,
          synergyIds,
          product: row.product.split(',').filter(i => i) ?? []
        }
        this.dialogTitle = 2
      } else {
        if (this.formId) {
          this.form = { ...this.$options.data().form }
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
    },
    // 添加成功的回调
    addHandler(value) {
      this.getList()
      this.formId = -1
      if(value.flag) {
        this.handleView({ id: value.data })
      }
    },
    // 修改成功的回调
    updateHandler(value) {
      this.getList()
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/activity/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `activities_${new Date().getTime()}.xlsx`)
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.activityDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>

<style scoped lang="scss">
.img-box {
  display: flex;
  align-items: center;
}

.justify-content {
  justify-content: center;
}

.infinite-list {
  padding: 0;

  .infinite-list-item {
    margin: 8px 0;
    list-style: none;
  }

  .cus_text {
    & > div {
      margin: 10px auto;

      & > span:first-child {
        display: inline-block;
        width: 80px;
        font-weight: bolder;
        text-align: right;
        margin-right: 8px;
      }
    }
  }

  .flex {
    display: flex;
  }

  .items-center {
    align-items: center;
  }

  .flex-1 {
    flex: 1;
  }
}
</style>
